package com.zd.kiychen.service.impl;

import bo.QueueUseObjet;
import com.alibaba.fastjson.JSON;
import com.zd.kiychen.service.OrderPushService;
import dto.OrderDetailsDTO;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @program: sporadic
 * @description:
 * @author: LHD   QQ:1727865856
 * @create: 2019-11-23 09:12
 **/
@Service
public class OrderPushServiceImpl implements OrderPushService {
    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean addQueueMessage(QueueUseObjet message, Integer mid) {
        try {
            //如果Properties为空则说明不存在此队列
            Properties queProperties = rabbitAdmin.getQueueProperties("sporadic" + mid);
            //创建队列，并绑定exchange
            if (queProperties == null) {
                rabbitAdmin.declareQueue(new Queue("sporadic" + mid));
                rabbitAdmin.declareBinding(new Binding("sporadic"
                        , Binding.DestinationType.QUEUE
                        , "sporadic"
                        , "sporadic" + mid
                        , null));
                System.err.println("创建以及绑定Exchange成功！");

            }
            /*创建成功之后向队列添加信息*/
            rabbitTemplate.convertAndSend("sporadic", "sporadic" + mid, message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("队列消息发送失败！");
        }
    }

    @Override
    public QueueUseObjet getOrderInfo(Integer mid) {
        QueueUseObjet queueUseObjet=null;
        try{
            String queueName = "sporadic" + mid;
            queueUseObjet= (QueueUseObjet) rabbitTemplate.receiveAndConvert(queueName);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("无消息！");
        }
        return queueUseObjet;
    }
}
